/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package me.zhengjie.modules.biz.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.biz.domain.*;
import me.zhengjie.modules.biz.repository.*;
import me.zhengjie.modules.biz.service.BarCodeService;
import me.zhengjie.modules.biz.service.dto.BarCodeDto;
import me.zhengjie.modules.biz.service.dto.BarCodeQueryCriteria;
import me.zhengjie.modules.biz.service.dto.HazardousChemicalsDto;
import me.zhengjie.modules.biz.service.dto.HazardousChemicalsQueryCriteria;
import me.zhengjie.modules.biz.service.mapstruct.BarCodeMapper;
import me.zhengjie.modules.biz.service.mapstruct.HazardousChemicalsMapper;
import me.zhengjie.modules.biz.utils.BarcodeUtil;
import me.zhengjie.modules.biz.utils.QRCodeUtil;
import me.zhengjie.utils.FileUtil;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;
import me.zhengjie.utils.ValidationUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.Predicate;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.lang.System;
import java.util.*;

/**
 * @author Admin
 * @website https://eladmin.vip
 * @description 服务实现
 * @date 2023-03-03
 **/
@Service
@RequiredArgsConstructor
public class BarCodeServiceImpl implements BarCodeService {

    private final BarCodeRepository barCodeRepository;
    private final BarCodeMapper barCodeMapper;
    private final LabRepository labRepository;
    private final HazardousChemicalsRepository hazardousChemicalsRepository;
    private final HazardousChemicalsMapper hazardousChemicalsMapper;
    private final CabinetRepository cabinetRepository;
    private final SettingsRepository settingsRepository;
    private final HazardousChemicalsChangeRecordRepository hazardousChemicalsChangeRecordRepository;

    @Override
    public Map<String, Object> queryAll(BarCodeQueryCriteria criteria, Pageable pageable) {

        Specification<BarCode> specification = (Specification<BarCode>) (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<Predicate>();
            predicates.add(criteriaBuilder.equal(root.get("type").as(Integer.class), 4));
            if (criteria.getCreatedAt() != null) {
                predicates.add(criteriaBuilder.between(root.get("createdAt"), criteria.getCreatedAt().get(0), criteria.getCreatedAt().get(1)));
            }
            return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
        };
        Page<BarCode> page = barCodeRepository.findAll(specification, pageable);
        Page<BarCodeDto> dto = page.map(barCodeMapper::toDto);
        List<BarCodeDto> resultDto = dto.getContent();
        for (BarCodeDto barCodeDto : resultDto) {
            Lab lab = labRepository.findById(barCodeDto.getLabId()).orElseGet(Lab::new);
            barCodeDto.setLabName(lab.getName());
        }
        return PageUtil.toPage(dto);
    }

    @Override
    public List<BarCodeDto> queryAll(BarCodeQueryCriteria criteria) {
        List<BarCodeDto> res = barCodeMapper.toDto(barCodeRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
        for (BarCodeDto barCodeDto : res) {
            Lab lab = labRepository.findById(barCodeDto.getLabId()).orElseGet(Lab::new);
            barCodeDto.setLabName(lab.getName());
        }
        return res;
    }

    @Override
    @Transactional
    public BarCodeDto findById(Integer id) {
        BarCode barCode = barCodeRepository.findById(id).orElseGet(BarCode::new);
        ValidationUtil.isNull(barCode.getId(), "BarCode", "id", id);
        return barCodeMapper.toDto(barCode);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BarCodeDto create(BarCode resources) {
        BarCodeDto barCodeDto = barCodeMapper.toDto(barCodeRepository.save(resources));
        int id = barCodeDto.getId();
        String msg = "b".concat(generateNumber(id));
        String barBase64 = BarcodeUtil.barBase64(msg);
        BarCode barCode = barCodeRepository.findById(id).orElseGet(BarCode::new);
        resources.setId(id);
        resources.setBarCode(barBase64);
        Lab lab = labRepository.findById(barCodeDto.getLabId()).orElseGet(Lab::new);
        barCodeDto.setLabName(lab.getName());
        barCode.copy(resources);
        return barCodeMapper.toDto(barCodeRepository.save(barCode));

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(BarCode resources) {
        BarCode barCode = barCodeRepository.findById(resources.getId()).orElseGet(BarCode::new);
        ValidationUtil.isNull(barCode.getId(), "BarCode", "id", resources.getId());
        barCode.copy(resources);
        barCodeRepository.save(barCode);
    }

    @Override
    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            barCodeRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<BarCodeDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (BarCodeDto barCode : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("名称", barCode.getName());
            map.put("条码", barCode.getBarCode());
            map.put("类型", barCode.getType());
            map.put("存放地址", barCode.getLabId());
            map.put(" createdAt", barCode.getCreatedAt());
            map.put(" updatedAt", barCode.getUpdatedAt());
            map.put(" isDeleted", barCode.getIsDeleted());
            map.put("数量", barCode.getAmount());
            map.put("状态", barCode.getState());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public void printBarCode(Integer id, Integer type, HttpServletResponse response) {
//        if (type!=1) {
        String msg = "h".concat(generateNumber(id));
        HazardousChemicals hazardousChemicals = hazardousChemicalsRepository.findById(id).orElseGet(HazardousChemicals::new);
        String name = hazardousChemicals.getName().concat("_").concat(String.valueOf(id));
        if (hazardousChemicals.getType() == 1) {
            if (Objects.equals(hazardousChemicals.getCategory(), "1")) {
                String ChineseName = hazardousChemicals.getName().concat(" ").concat(String.valueOf(hazardousChemicals.getCapacity())).concat("(ml)");
                BarcodeUtil.printBarCode(msg, name, ChineseName, response);
            } else {
                if (hazardousChemicals.getUnit() == 1) {
                    String ChineseName = hazardousChemicals.getName().concat(" ").concat(String.valueOf(1)).concat("(个)");
                    BarcodeUtil.printBarCode(msg, name, ChineseName, response);
                } else if (hazardousChemicals.getUnit() == 2) {
                    String ChineseName = hazardousChemicals.getName().concat(" ").concat(String.valueOf(1)).concat("(台)");
                    BarcodeUtil.printBarCode(msg, name, ChineseName, response);
                } else {
                    String ChineseName = hazardousChemicals.getName().concat(" ").concat(String.valueOf(1)).concat("(套)");
                    BarcodeUtil.printBarCode(msg, name, ChineseName, response);
                }
//               String ChineseName = hazardousChemicals.getName().concat(" ").concat(String.valueOf(1)).concat("()");
            }
        } else if (hazardousChemicals.getType() == 3) {
            String ChineseName = hazardousChemicals.getName().concat(" ").concat(String.valueOf(hazardousChemicals.getCapacity())).concat("(ml)");
            BarcodeUtil.printBarCode(msg, name, ChineseName, response);
        } else {
            if (Objects.equals(hazardousChemicals.getUnit(), "1")) {
                String ChineseName = hazardousChemicals.getName().concat(" ").concat(String.valueOf(1)).concat("(支)");
                BarcodeUtil.printBarCode(msg, name, ChineseName, response);
            } else {
                String ChineseName = hazardousChemicals.getName().concat(" ").concat(String.valueOf(hazardousChemicals.getCapacity())).concat("(ml)");
                BarcodeUtil.printBarCode(msg, name, ChineseName, response);
            }
        }


        ////            BarCode barCode = barCodeRepository.findById(id).orElseGet(BarCode::new);
//            String msg = "h".concat(generateNumber(id));
//            HazardousChemicals hazardousChemicals = hazardousChemicalsRepository.findById(id).orElseGet(HazardousChemicals::new);
//            String name = hazardousChemicals.getName().concat("_").concat(String.valueOf(id));
//            if (hazardousChemicals.getCountType()==1){
//                String ChineseName = hazardousChemicals.getName().concat(" ").concat(String.valueOf(hazardousChemicals.getAmount())).concat("(ml)");
//                BarcodeUtil.printBarCode(msg,name,ChineseName,response);
//
//            }else {
//                String ChineseName = hazardousChemicals.getName().concat(" ").concat(String.valueOf(hazardousChemicals.getAmount())).concat("(g)");
//                BarcodeUtil.printBarCode(msg,name,ChineseName,response);
//
//            }
//
//        }else {
//            String msg = "b".concat(generateNumber(id));
//            BarCode barCode = barCodeRepository.findById(id).orElseGet(BarCode::new);
//            String name = barCode.getName().concat("_").concat(String.valueOf(id));
//
//            String ChineseName = barCode.getName().concat(" ").concat(String.valueOf(barCode.getAmount())).concat("(个)");
//            BarcodeUtil.printBarCode(msg,name,ChineseName,response);
//        }
//        }

    }


    public void printQRCode(Integer id, Integer type, HttpServletResponse response) {

        List<Settings> settingsList = settingsRepository.findSizeByKey();
        HashMap<String, Integer> config = new HashMap<>();
        for (Settings settings : settingsList) {
            config.put(settings.getKey(), Convert.toInt(settings.getValue()));
        }
        if (type != 1) {
//            BarCode barCode = barCodeRepository.findById(id).orElseGet(BarCode::new);
            String msg = "h".concat(generateNumber(id));
            HazardousChemicals hazardousChemicals = hazardousChemicalsRepository.findById(id).orElseGet(HazardousChemicals::new);
//            System.out.println(hazardousChemicals);

            String name = hazardousChemicals.getName().concat("_").concat(String.valueOf(id));
//            if (hazardousChemicals.getCountType() == 1) {
            String ChineseName = hazardousChemicals.getName().concat(" ").concat(String.valueOf(hazardousChemicals.getAmount())).concat("(ml)");
            ArrayList<String> descList = new ArrayList<>();
            if (hazardousChemicals.getType() == 1) {
                descList.add("名称:".concat(hazardousChemicals.getName()));
                if (Objects.equals(hazardousChemicals.getCategory(), "1")) {
                    descList.add("规格:".concat(String.valueOf(hazardousChemicals.getCapacity()).concat("(")).concat(Convert.toStr(hazardousChemicals.getUnit())).concat(")"));
                } else {
//                    descList.add("单位:".concat("(").concat(hazardousChemicals.getUnit()).concat(")"));
                    if (hazardousChemicals.getUnit() == 1) {
                        descList.add("单位:个");
                    } else if (hazardousChemicals.getUnit() == 2) {
                        descList.add("单位:台");

                    } else {
                        descList.add("单位:套");
                    }
                }
                if (hazardousChemicals.getType() == 1) {
                    descList.add("类型:玻璃器皿");
                } else if (hazardousChemicals.getType() == 2) {
                    descList.add("类型:实验耗材");
                } else if (hazardousChemicals.getType() == 3) {
                    descList.add("类型:采样工具");
                } else if (hazardousChemicals.getType() == 4) {
                    descList.add("类型:仪器设备");
                }
                QRCodeUtil.printQRCode(msg, name, descList, config, hazardousChemicals.getType(), response);
            } else if (hazardousChemicals.getType() == 3) {
                descList.add("名称:".concat(hazardousChemicals.getName()));

//                    descList.add("规格:".concat(String.valueOf(hazardousChemicals.getCapacity()).concat("(ml)")));
                descList.add("类型:".concat(hazardousChemicals.getGrade()));
                Cabinet cabinet = cabinetRepository.findById(hazardousChemicals.getCabinetId()).orElseGet(Cabinet::new);
                descList.add("试剂柜:" + cabinet.getName());
                QRCodeUtil.printQRCode(msg, name, descList, config, hazardousChemicals.getType(), response);
            } else {
                descList.add("参数:".concat(hazardousChemicals.getName()));
                descList.add("有效期:".concat(String.valueOf(hazardousChemicals.getExpirationDate())));
                descList.add("类型:" + hazardousChemicals.getCategory());
                QRCodeUtil.printQRCode(msg, name, descList, config, hazardousChemicals.getType(), response);
            }
        }
    }

    @Override
    public void bulkPrint(String data, Integer type, HttpServletResponse response) {

        String filePath = "/tmp/barCodeBulkDownload/";
        String zipFilePath = "/tmp/BarCodePicture.zip";
        File file = new File(filePath);
        File zipFile = new File(zipFilePath);
        if (file.exists()) {
            System.out.println(deleteFolder(file));
            System.out.println(deleteFolder(zipFile));
        }
        file.mkdirs();
        int[] ids = StrUtil.splitToInt(data, ",");
        if (type != 4) {
            for (int i = 0; i < ids.length; i++) {
                String msg = "h".concat(generateNumber(ids[i]));
                HazardousChemicals hazardousChemicals = hazardousChemicalsRepository.findById(ids[i]).orElseGet(HazardousChemicals::new);
                String name = hazardousChemicals.getName().concat("_").concat(String.valueOf(ids[i]));
                String fileName = filePath.concat(name).concat(".png");
                if (hazardousChemicals.getCountType() == 1) {
                    String ChineseName = hazardousChemicals.getName().concat(" ").concat(String.valueOf(hazardousChemicals.getAmount())).concat("(ml)");
                    BarcodeUtil.bulkPrintBarCode(msg, name, ChineseName, fileName);

                } else {
                    String ChineseName = hazardousChemicals.getName().concat(" ").concat(String.valueOf(hazardousChemicals.getAmount())).concat("(g)");
                    BarcodeUtil.bulkPrintBarCode(msg, name, ChineseName, fileName);
                }
            }
        } else {
            for (int i = 0; i < ids.length; i++) {
                String msg = "b".concat(generateNumber(ids[i]));
                BarCode barCode = barCodeRepository.findById(ids[i]).orElseGet(BarCode::new);
                String name = barCode.getName().concat("_").concat(String.valueOf(ids[i]));
                String fileName = filePath.concat(name).concat(".png");
                String ChineseName = barCode.getName().concat(" ").concat(String.valueOf(barCode.getAmount())).concat("(个)");
                BarcodeUtil.bulkPrintBarCode(msg, name, ChineseName, fileName);
            }
        }


        BarcodeUtil.tozip(filePath, "/tmp", "BarCodePicture");
        BarcodeUtil.downFile("/tmp", "BarCodePicture.zip", response);

    }

    public void bulkPrintQRCode(String data, Integer type, HttpServletResponse response) {

        String filePath = "/tmp/QRCodeBulkDownload/";
        String zipFilePath = "/tmp/QRCodePicture.zip";
//        String filePath = "C:\\Users\\18715\\Desktop\\QRCodeBulkDownload\\";
//        String zipFilePath = "C:\\Users\\18715\\Desktop\\QRCodePicture.zip";
        File file = new File(filePath);
        File zipFile = new File(zipFilePath);
        if (file.exists()) {
            System.out.println(deleteFolder(file));
            System.out.println(deleteFolder(zipFile));
        }
        file.mkdirs();
        int[] ids = StrUtil.splitToInt(data, ",");
        if (type != 4) {
            for (int i = 0; i < ids.length; i++) {
                String msg = "h".concat(generateNumber(ids[i]));
                HazardousChemicals hazardousChemicals = hazardousChemicalsRepository.findById(ids[i]).orElseGet(HazardousChemicals::new);
                String name = hazardousChemicals.getName().concat("_").concat(String.valueOf(ids[i]));
                String fileName = name.concat(".png");
                if (hazardousChemicals.getCountType() == 1) {
                    String ChineseName = hazardousChemicals.getName().concat(" ").concat(String.valueOf(hazardousChemicals.getAmount())).concat("(ml)");
                    ArrayList<String> descList = new ArrayList<>();
                    descList.add("名称:".concat(hazardousChemicals.getName()));
                    if (hazardousChemicals.getCountType() == 1) {
                        descList.add("容量:".concat(String.valueOf(hazardousChemicals.getCapacity()).concat("(ml)")));
                    } else {
                        descList.add("容量:".concat(String.valueOf(hazardousChemicals.getCapacity()).concat("(g)")));
                    }
                    if (hazardousChemicals.getType() == 1) {
                        descList.add("类型:耗材");
                    } else if (hazardousChemicals.getType() == 2) {
                        descList.add("类型:标准物质");
                    } else {
                        descList.add("类型:危化品");
                    }
                    if (hazardousChemicals.getDangerClasses() == 1) {
                        descList.add("危险等级:普通");
                    } else {
                        descList.add("危险等级:危险");
                    }
                    QRCodeUtil.bulkPrintBarCode(msg, name, descList, filePath, fileName);

                } else {
                    String ChineseName = hazardousChemicals.getName().concat(" ").concat(String.valueOf(hazardousChemicals.getAmount())).concat("(g)");
                    ArrayList<String> descList = new ArrayList<>();
                    descList.add("名称:".concat(hazardousChemicals.getName()));
                    if (hazardousChemicals.getCountType() == 1) {
                        descList.add("容量:".concat(String.valueOf(hazardousChemicals.getCapacity()).concat("(ml)")));
                    } else {
                        descList.add("容量:".concat(String.valueOf(hazardousChemicals.getCapacity()).concat("(g)")));
                    }
                    if (hazardousChemicals.getType() == 1) {
                        descList.add("类型:耗材");
                    } else if (hazardousChemicals.getType() == 2) {
                        descList.add("类型:标准物质");
                    } else {
                        descList.add("类型:危化品");
                    }
                    if (hazardousChemicals.getDangerClasses() == 1) {
                        descList.add("危险等级:普通");
                    } else {
                        descList.add("危险等级:危险");
                    }
                    QRCodeUtil.bulkPrintBarCode(msg, name, descList, filePath, fileName);
                }
            }
        } else {
            for (int i = 0; i < ids.length; i++) {
                String msg = "b".concat(generateNumber(ids[i]));
                BarCode barCode = barCodeRepository.findById(ids[i]).orElseGet(BarCode::new);
                String name = barCode.getName().concat("_").concat(String.valueOf(ids[i]));
                String fileName = filePath.concat(name).concat(".png");
                String ChineseName = barCode.getName().concat(" ").concat(String.valueOf(barCode.getAmount())).concat("(个)");
                ArrayList<String> descList = new ArrayList<>();
                descList.add("名称:".concat(barCode.getName()));
                QRCodeUtil.bulkPrintBarCode(msg, name, descList, filePath, fileName);
            }
        }
        BarcodeUtil.tozip(filePath, "/tmp", "QRCodePicture");
        BarcodeUtil.downFile("/tmp", "QRCodePicture.zip", response);

    }

    @Override
    public void bulkPrintSearchSundries(BarCodeQueryCriteria criteria, HttpServletResponse response) {
        String filePath = "/tmp/barCodeBulkDownload/";
        String zipFilePath = "/tmp/BarCodePicture.zip";
        File file = new File(filePath);
        File zipFile = new File(zipFilePath);
        if (file.exists()) {
            System.out.println(deleteFolder(file));
            System.out.println(deleteFolder(zipFile));
        }
        file.mkdirs();
        List<BarCodeDto> res = barCodeMapper.toDto(barCodeRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
        for (BarCodeDto barCodeDto : res) {
            String msg = "b".concat(generateNumber(barCodeDto.getId()));
            BarCode barCode = barCodeRepository.findById(barCodeDto.getId()).orElseGet(BarCode::new);
            String name = barCode.getName().concat("_").concat(String.valueOf(barCodeDto.getId()));
            String fileName = filePath.concat(name).concat(".png");
            String ChineseName = barCode.getName().concat(" ").concat(String.valueOf(barCode.getAmount())).concat("(个)");
            BarcodeUtil.bulkPrintBarCode(msg, name, ChineseName, fileName);
        }
        BarcodeUtil.tozip(filePath, "/tmp", "BarCodePicture");
        BarcodeUtil.downFile("/tmp", "BarCodePicture.zip", response);
    }

    @Override
    public void bulkPrintQRCodeSearchSundries(BarCodeQueryCriteria criteria, HttpServletResponse response) {
        String filePath = "/tmp/QRCodeBulkDownload/";
        String zipFilePath = "/tmp/QRCodePicture.zip";
        File file = new File(filePath);
        File zipFile = new File(zipFilePath);
        if (file.exists()) {
            System.out.println(deleteFolder(file));
            System.out.println(deleteFolder(zipFile));
        }
        file.mkdirs();
        List<BarCodeDto> res = barCodeMapper.toDto(barCodeRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
        for (BarCodeDto barCodeDto : res) {
            String msg = "b".concat(generateNumber(barCodeDto.getId()));
            BarCode barCode = barCodeRepository.findById(barCodeDto.getId()).orElseGet(BarCode::new);
            String name = barCode.getName().concat("_").concat(String.valueOf(barCodeDto.getId()));
            String fileName = filePath.concat(name).concat(".png");
            String ChineseName = barCode.getName().concat(" ").concat(String.valueOf(barCode.getAmount())).concat("(个)");
            ArrayList<String> descList = new ArrayList<>();
            descList.add("名称:".concat(barCode.getName()));
            QRCodeUtil.bulkPrintBarCode(msg, name, descList, filePath, fileName);
        }
        BarcodeUtil.tozip(filePath, "/tmp", "QRCodePicture");
        BarcodeUtil.downFile("/tmp", "QRCodePicture.zip", response);
    }

    @Override
    public void bulkPrintQRCodeSearchHC(HazardousChemicalsQueryCriteria criteria, HttpServletResponse response) {
        String filePath = "/tmp/QRCodeBulkDownload/";
        String zipFilePath = "/tmp/QRCodePicture.zip";
        File file = new File(filePath);
        File zipFile = new File(zipFilePath);
        if (file.exists()) {
            System.out.println(deleteFolder(file));
            System.out.println(deleteFolder(zipFile));
        }
        file.mkdirs();
        List<HazardousChemicalsDto> res = hazardousChemicalsMapper.toDto(hazardousChemicalsRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
        for (HazardousChemicalsDto hazardousChemicalsDto : res) {
            String msg = "h".concat(generateNumber(hazardousChemicalsDto.getId()));
            HazardousChemicals hazardousChemicals = hazardousChemicalsRepository.findById(hazardousChemicalsDto.getId()).orElseGet(HazardousChemicals::new);
            String name = hazardousChemicals.getName().concat("_").concat(String.valueOf(hazardousChemicalsDto.getId()));
            String fileName = name.concat(".png");
            if (hazardousChemicals.getCountType() == 1) {
                String ChineseName = hazardousChemicals.getName().concat(" ").concat(String.valueOf(hazardousChemicals.getAmount())).concat("(ml)");
                ArrayList<String> descList = new ArrayList<>();
                descList.add("名称:".concat(hazardousChemicals.getName()));
                if (hazardousChemicals.getCountType() == 1) {
                    descList.add("容量:".concat(String.valueOf(hazardousChemicals.getCapacity()).concat("(ml)")));
                } else {
                    descList.add("容量:".concat(String.valueOf(hazardousChemicals.getCapacity()).concat("(g)")));
                }
                if (hazardousChemicals.getType() == 1) {
                    descList.add("类型:耗材");
                } else if (hazardousChemicals.getType() == 2) {
                    descList.add("类型:标准物质");
                } else {
                    descList.add("类型:危化品");
                }
                if (hazardousChemicals.getDangerClasses() == 1) {
                    descList.add("危险等级:普通");
                } else {
                    descList.add("危险等级:危险");
                }
                QRCodeUtil.bulkPrintBarCode(msg, name, descList, filePath, fileName);

            } else {
                String ChineseName = hazardousChemicals.getName().concat(" ").concat(String.valueOf(hazardousChemicals.getAmount())).concat("(g)");
                ArrayList<String> descList = new ArrayList<>();
                descList.add("名称:".concat(hazardousChemicals.getName()));
                if (hazardousChemicals.getCountType() == 1) {
                    descList.add("容量:".concat(String.valueOf(hazardousChemicals.getCapacity()).concat("(ml)")));
                } else {
                    descList.add("容量:".concat(String.valueOf(hazardousChemicals.getCapacity()).concat("(g)")));
                }
                if (hazardousChemicals.getType() == 1) {
                    descList.add("类型:耗材");
                } else if (hazardousChemicals.getType() == 2) {
                    descList.add("类型:标准物质");
                } else {
                    descList.add("类型:危化品");
                }
                if (hazardousChemicals.getDangerClasses() == 1) {
                    descList.add("危险等级:普通");
                } else {
                    descList.add("危险等级:危险");
                }
                QRCodeUtil.bulkPrintBarCode(msg, name, descList, filePath, fileName);
            }
        }
        BarcodeUtil.tozip(filePath, "/tmp", "QRCodePicture");
        BarcodeUtil.downFile("/tmp", "QRCodePicture.zip", response);
    }

    @Override
    public void bulkPrintSearchHC(HazardousChemicalsQueryCriteria criteria, HttpServletResponse response) {
        String filePath = "/tmp/barCodeBulkDownload/";
        String zipFilePath = "/tmp/BarCodePicture.zip";
        File file = new File(filePath);
        File zipFile = new File(zipFilePath);
        if (file.exists()) {
            System.out.println(deleteFolder(file));
            System.out.println(deleteFolder(zipFile));
        }
        file.mkdirs();
        List<HazardousChemicalsDto> res = hazardousChemicalsMapper.toDto(hazardousChemicalsRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
        for (HazardousChemicalsDto hazardousChemicalsDto : res) {
            String msg = "h".concat(generateNumber(hazardousChemicalsDto.getId()));
            HazardousChemicals hazardousChemicals = hazardousChemicalsRepository.findById(hazardousChemicalsDto.getId()).orElseGet(HazardousChemicals::new);
            String name = hazardousChemicals.getName().concat("_").concat(String.valueOf(hazardousChemicalsDto.getId()));
            String fileName = filePath.concat(name).concat(".png");
            if (hazardousChemicals.getCountType() == 1) {
                String ChineseName = hazardousChemicals.getName().concat(" ").concat(String.valueOf(hazardousChemicals.getAmount())).concat("(ml)");
                BarcodeUtil.bulkPrintBarCode(msg, name, ChineseName, fileName);

            } else {
                String ChineseName = hazardousChemicals.getName().concat(" ").concat(String.valueOf(hazardousChemicals.getAmount())).concat("(g)");
                BarcodeUtil.bulkPrintBarCode(msg, name, ChineseName, fileName);
            }
        }
        BarcodeUtil.tozip(filePath, "/tmp", "BarCodePicture");
        BarcodeUtil.downFile("/tmp", "BarCodePicture.zip", response);
    }


    @Override
    public void showQRCode(Integer id, Integer type, Integer serialNumber, HttpServletResponse response) {
//        if (type!=4){
        List<Settings> settingsList = settingsRepository.findSizeByKey();

        String msg = "h".concat(generateNumber(id));
        HazardousChemicals hazardousChemicals = hazardousChemicalsRepository.findById(id).orElseGet(HazardousChemicals::new);
        String name = hazardousChemicals.getName().concat("_").concat(String.valueOf(id));
        String ChineseName = hazardousChemicals.getName().concat(" ").concat(String.valueOf(hazardousChemicals.getAmount())).concat("(").concat(Convert.toStr(hazardousChemicals.getUnit())).concat(")");
        setDescList(serialNumber, response, msg, hazardousChemicals, name, settingsList);
    }

    private void setDescList(Integer serialNumber, HttpServletResponse response, String msg, HazardousChemicals hazardousChemicals, String name, List<Settings> settingsList) {
        ArrayList<String> descList = new ArrayList<>();
        HashMap<String, Integer> config = new HashMap<>();
        for (Settings settings : settingsList) {
            config.put(settings.getKey(), Convert.toInt(settings.getValue()));
        }
        if (hazardousChemicals.getType() == HazardousChemicals.QI_CAI) {//器材
            descList.add("名称:".concat(hazardousChemicals.getName()));
            if (Objects.equals(hazardousChemicals.getCategory(), "1")) {
                descList.add("规格:".concat(String.valueOf(hazardousChemicals.getCapacity()).concat("(")).concat(Convert.toStr(hazardousChemicals.getUnit())).concat(")"));
            } else {
                if (hazardousChemicals.getUnit() == 1) {
                    descList.add("单位:个");
                } else if (hazardousChemicals.getUnit() == 2) {
                    descList.add("单位:台");
                } else {
                    descList.add("单位:套");
                }
            }
            if (hazardousChemicals.getType() == 1) {
                descList.add("类型:玻璃器皿");
            } else if (hazardousChemicals.getType() == 2) {
                descList.add("类型:实验耗材");
            } else if (hazardousChemicals.getType() == 3) {
                descList.add("类型:采样工具");
            } else if (hazardousChemicals.getType() == 4) {
                descList.add("类型:仪器设备");
            }
            QRCodeUtil.showQRCode(msg, name, serialNumber, descList, config, hazardousChemicals.getType(), response);
        } else if (hazardousChemicals.getType() == HazardousChemicals.HUA_XUE_SHI_JI) {//试剂
            descList.add("名称:".concat(hazardousChemicals.getName()));

//                    descList.add("规格:".concat(String.valueOf(hazardousChemicals.getCapacity()).concat("(ml)")));
            descList.add("类型:".concat(hazardousChemicals.getGrade()));
            Cabinet cabinet = cabinetRepository.findById(hazardousChemicals.getCabinetId()).orElseGet(Cabinet::new);
            descList.add("试剂柜:" + cabinet.getName());
            QRCodeUtil.showQRCode(msg, name, serialNumber, descList, config, hazardousChemicals.getType(), response);
        } else if (hazardousChemicals.getType() == HazardousChemicals.BIAO_ZHUN_WU_ZHI) {//试剂 {//标准物质 2
            descList.add("参数:".concat(hazardousChemicals.getName()));
            String expirationDate = String.valueOf(hazardousChemicals.getExpirationDate());
            String[] time = expirationDate.split(" ");
            descList.add("有效期:".concat(time[0]));
            descList.add("类型:" + hazardousChemicals.getCategory());
            QRCodeUtil.showQRCode(msg, name, serialNumber, descList, config, hazardousChemicals.getType(), response);
        }
    }

    @Override
    public void showBarCode(Integer id, Integer type, Integer serialNumber, HttpServletResponse response) {
//        if (type!=4){
        //HazardousChemicalsChangeRecord hazardousChemicalsChangeRecord = hazardousChemicalsChangeRecordRepository.findById(id).orElseGet(HazardousChemicalsChangeRecord::new);
        String msg = "h".concat(generateNumber(id));
        HazardousChemicals hazardousChemicals = hazardousChemicalsRepository.findById(id).orElseGet(HazardousChemicals::new);
        String name = hazardousChemicals.getName().concat("_").concat(String.valueOf(id));
        if (hazardousChemicals.getType() == 1) {
            if (Objects.equals(hazardousChemicals.getCategory(), "1")) {
                String ChineseName = hazardousChemicals.getName().concat(" ").concat(String.valueOf(hazardousChemicals.getCapacity())).concat("(ml)");
                BarcodeUtil.showBarCode(msg, name, serialNumber, ChineseName, response);
            } else {
                if (hazardousChemicals.getUnit() == 1) {
                    String ChineseName = hazardousChemicals.getName().concat(" ").concat(String.valueOf(1)).concat("(个)");
                    BarcodeUtil.showBarCode(msg, name, serialNumber, ChineseName, response);
                } else if (hazardousChemicals.getUnit() == 2) {
                    String ChineseName = hazardousChemicals.getName().concat(" ").concat(String.valueOf(1)).concat("(台)");
                    BarcodeUtil.showBarCode(msg, name, serialNumber, ChineseName, response);
                } else {
                    String ChineseName = hazardousChemicals.getName().concat(" ").concat(String.valueOf(1)).concat("(套)");
                    BarcodeUtil.showBarCode(msg, name, serialNumber, ChineseName, response);

                }
//               String ChineseName = hazardousChemicals.getName().concat(" ").concat(String.valueOf(1)).concat("()");
            }
        } else if (hazardousChemicals.getType() == 3) {
            String ChineseName = hazardousChemicals.getName().concat(" ").concat(String.valueOf(hazardousChemicals.getCapacity())).concat("(ml)");
            BarcodeUtil.showBarCode(msg, name, serialNumber, ChineseName, response);
        } else {
            if (Objects.equals(hazardousChemicals.getUnit(), "1")) {
                String ChineseName = hazardousChemicals.getName().concat(" ").concat(String.valueOf(1)).concat("(支)");
                BarcodeUtil.showBarCode(msg, name, serialNumber, ChineseName, response);
            } else {
                String ChineseName = hazardousChemicals.getName().concat(" ").concat(String.valueOf(hazardousChemicals.getCapacity())).concat("(ml)");
                BarcodeUtil.showBarCode(msg, name, serialNumber, ChineseName, response);
            }
        }


//        }else {
//            String msg = "b".concat(generateNumber(id));
//            BarCode barCode = barCodeRepository.findById(id).orElseGet(BarCode::new);
//            String name = barCode.getName().concat("_").concat(String.valueOf(id));
//
//            String ChineseName = barCode.getName().concat(" ").concat(String.valueOf(barCode.getAmount())).concat("(个)");
//            BarcodeUtil.showBarCode(msg,name,serialNumber,ChineseName,response);
//        }
    }


    private String generateNumber(int num) {
        StringBuffer msg = new StringBuffer("000000000000");
        String numString = String.valueOf(num);
        int start = 12 - numString.length();
        msg.replace(start, 12, numString);

        return msg.toString();
    }

    private boolean deleteFolder(File file) {
        // 当传入的是文件时，直接删除
        if (file.isFile())
            return file.delete();

        // 当传入的是文件夹时
        File[] files = file.listFiles();
        // 空文件夹，直接删除
        if (files == null || files.length == 0)
            return file.delete();
        // 非空文件夹，遍历删除
        for (File f : files) {
            if (f.isFile())              // 文件直接删除
                f.delete();
            else if (f.isDirectory())   // 文件夹递归删除
                deleteFolder(f);
        }

        // 最后删除最外层空文件夹
        return file.delete();
    }
}
